<template>
    <el-card>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
            :size="formSize" status-icon v-loading="loading">
            <el-form-item label="事件类别" prop="RYD_TypeId">
                <el-select v-model="ruleForm.RYD_TypeId" placeholder="请选择事件类别">
                    <el-option :label="item.ryD_DemandTypeName" :value="item.ryD_DemandTypeNo"
                        v-for="(item, index) in levelColumnsDemandType" v-bind:key="index" />
                </el-select>
            </el-form-item>
            <el-form-item label="重要级别" prop="RYD_Level">
                <el-select v-model="ruleForm.RYD_Level" placeholder="请选择重要级别">
                    <el-option :label="item.ryD_DemandLevelName" :value="item.ryD_DemandLevelNo"
                        v-for="(item, index) in levelColumns" v-bind:key="index" />
                </el-select>
            </el-form-item>
            <el-form-item label="姓名" prop="RYD_UserName">
                <el-input v-model="ruleForm.RYD_UserName" disabled />
            </el-form-item>
            <el-form-item label="位置" prop="RYD_UserAddress">
                <el-input v-model="ruleForm.RYD_UserAddress" />
            </el-form-item>
            <el-form-item label="IP地址" prop="RYD_UserIp">
                <el-input v-model="ruleForm.RYD_UserIp" />
            </el-form-item>
            <el-form-item label="联系方式" prop="RYD_UserPhone">
                <el-input v-model="ruleForm.RYD_UserPhone" />
            </el-form-item>
            <el-form-item label="需求详情" prop="RYD_DemandDetails">
                <el-input v-model="ruleForm.RYD_DemandDetails" type="textarea" rows="3" />
            </el-form-item>
            <el-form-item label="文件上传">
                <el-upload action="/api/UpImage" :headers="imageHeaders" :on-exceed="exceed" v-model:file-list="fileArr"
                    accept="image/*" :limit="3" list-type="picture-card" :auto-upload="false" ref="upload"
                    style="position: relative;" :on-success="successFile" :show-file-list="true">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    <template #file="{ file }">
                        <el-image style="width: 100%; height: 100%" ref="fileImage" :src="file.url"
                            :preview-src-list="[file.url]" class="imageFile" />
                        <span class="removeSpan" @click="handleRemove(file)">
                            <el-icon>
                                <Delete />
                            </el-icon>
                        </span>
                    </template>
                </el-upload>

            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)" v-if="props.editDemandId == null">提交
                </el-button>
                <el-button type="primary" @click="submitForm2(ruleFormRef)" v-else>重新提交</el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>

        </el-form>
    </el-card>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
        <span>{{ dialogText }}</span>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="dialogVisible = false">确定</el-button>
            </span>
        </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible2" title="提示" width="30%">
        <span>是否使用上一次的基础信息：
            <br />姓名：{{ ruleFormRes.ryD_UserName }}
            <br />位置：{{ ruleFormRes.ryD_UserAddress }}
            <br />IP地址：{{ ruleFormRes.ryD_UserIp }}
            <br />联系方式：{{ ruleFormRes.ryD_UserPhone }}
        </span>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible2 = false">否</el-button>
                <el-button type="primary" @click="lastDemand">
                    确认使用
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>
  
<script setup>
import { inject, reactive, ref } from 'vue'
// eslint-disable-next-line no-unused-vars
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'

import axios from '@/utils/axios'
// eslint-disable-next-line no-unused-vars
import { ElNotification } from 'element-plus';

import { useRouter } from 'vue-router';

const router = useRouter();
// eslint-disable-next-line no-undef
const props = defineProps(['editDemandId', 'showFallback']);

const loading = ref(true)

const formSize = ref('default')
const ruleFormRef = ref()
const ruleForm = ref({
    RYD_UserName: '',
    RYD_UserAddress: '',
    RYD_UserIp: '',
    RYD_UserPhone: '',
    RYD_TypeId: '',
    RYD_Level: '',
    RYD_DemandDetails: '',
})
var ruleFormRes = ref({
    ryD_UserName: '',
    ryD_UserAddress: '',
    ryD_UserIp: '',
    ryD_UserPhone: '',
});
let imageHeaders = {
    'X-Token': getToken()
}
function getToken() {
    try {
        var token = sessionStorage.getItem('token');
        if (sessionStorage.getItem('RYD_UserId') != null) {
            token += ";" + sessionStorage.getItem('RYD_UserId')
        }
        return token;
    } catch (error) {
        return null;
    }
}
let levelColumns = ref();
let RYD_UserId = inject('RYD_UserId');
let isDemandNum = inject('isDemandNum');
let RYD_Company = ref();
// const disabled = ref(false)
let levelColumnsDemandType = ref();
let fileArr = ref([]);
let fileImage = ref();

let dialogVisible = ref(false)

let dialogVisible2 = ref(false)
let dialogTitle = ref("提示")

let dialogText = ref('')

const rules = reactive({
    RYD_UserName: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
    ],
    RYD_UserAddress: [
        { required: true, message: '请输入所在位置', trigger: 'blur' },
    ],
    RYD_UserPhone: [
        { required: true, message: '请输入分机号或者手机号', trigger: 'blur' },
    ],
    RYD_TypeId: [
        {
            required: true,
            message: '请选择事件类别',
            trigger: 'change',
        },
    ],
    RYD_Level: [
        {
            required: true,
            message: '请选择重要级别',
            trigger: 'change',
        },
    ],
    RYD_DemandDetails: [
        { required: true, message: '请输入需求详情', trigger: 'blur' },
    ],
})
let upload = ref();

const lastDemand = () => {
    dialogVisible2.value = false;
    ruleForm.value.RYD_UserName = ruleFormRes.value.ryD_UserName;
    ruleForm.value.RYD_UserAddress = ruleFormRes.value.ryD_UserAddress;
    ruleForm.value.RYD_UserIp = ruleFormRes.value.ryD_UserIp;
    ruleForm.value.RYD_UserPhone = ruleFormRes.value.ryD_UserPhone;
}

// let srcList = ref([]);
const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid) => {
        if (valid) {

            if (fileArr.value.length != 0) {
                upload.value.submit();
            } else {
                addDemand();
            }
        }
    })
}
const submitForm2 = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid) => {
        if (valid) {
            let lengthFile = fileArr.value.length;
            for (let i = 0; i < fileArr.value.length; i++) {
                if (fileArr.value[i].status == 'success') {
                    lengthFile--;
                }
            }
            if (lengthFile != 0) {
                upload.value.submit();
            } else {
                addDemand2();
            }
        }
    })
}
let urlImage = "";
const successFile = (res, item) => {
    fileArr.value.splice(fileArr.value.indexOf(item), 1)
    urlImage += res + "|";

    let lengthFile = fileArr.value.length;
    for (let i = 0; i < fileArr.value.length; i++) {
        if (fileArr.value[i].status == 'success') {
            lengthFile--;
        }
    }
    if (lengthFile == 0) {
        if (props.editDemandId == null) {
            addDemand();
        } else {
            addDemand2();
        }
    }
}
const addDemand = () => {
    loading.value = true;
    let urlImageR = urlImage + "";
    urlImage = "";
    axios({
        method: 'post',
        url: '/api/AddDemand',
        data: {
            ...ruleForm.value,
            RYD_Files: urlImageR,
            RYD_UserId: RYD_UserId,
            RYD_Company: RYD_Company.value,
        }
    }).then(res => {
        loading.value = false;
        if (res != "") {
            resetForm(ruleFormRef.value);
            dialogVisible.value = true;
            dialogText.value = "需求提交成功，已将需求内容分配给IT人员，请等待IT处理。"
            isDemandNum.isDemandNum = isDemandNum.isDemandNum == 1 ? 2 : 1;
        } else {
            dialogVisible.value = true;
            dialogText.value = "需求提交失败，请检查订单信息或刷新页面。"

            ElNotification({
                title: '提示',
                message: '需求提交失败，请检查订单信息或刷新页面。',
                type: 'error',
                duration: 10000
            })
        }

    }).catch(() => {
        loading.value = false;
        dialogVisible.value = true;
        dialogText.value = "需求提交失败，请检查订单信息或刷新页面。"
        ElNotification({
            title: '提示',
            message: '需求提交失败，请检查订单信息或刷新页面。',
            type: 'error',
            duration: 10000
        })
    })
}
const addDemand2 = () => {
    loading.value = true;
    let urlImageR = urlImage + "";
    urlImage = "";
    axios({
        method: 'post',
        url: '/api/AddDemand2',
        data: {
            ...ruleForm.value,
            RYD_Files: urlImageR,
            RYD_UserId: RYD_UserId,
            RYD_Company: RYD_Company.value,
            RYD_DemandId: props.editDemandId
        }
    }).then(res => {
        loading.value = false;
        if (res != "") {
            resetForm(ruleFormRef.value);
            dialogVisible.value = true;
            dialogText.value = "需求提交成功，已将需求内容分配给IT人员，请等待IT处理。"
            setTimeout(() => {
                router.go(0);
            }, 500);
        } else {
            dialogVisible.value = true;
            dialogText.value = "需求提交失败，请检查订单信息或刷新页面。"

            ElNotification({
                title: '提示',
                message: '需求提交失败，请检查订单信息或刷新页面。',
                type: 'error',
                duration: 10000
            })
        }

    }).catch(() => {
        loading.value = false;
        dialogVisible.value = true;
        dialogText.value = "需求提交失败，请检查订单信息或刷新页面。"
        ElNotification({
            title: '提示',
            message: '需求提交失败，请检查订单信息或刷新页面。',
            type: 'error',
            duration: 10000
        })
    })
}
const exceed = () => {

    ElNotification({
        title: '提示',
        message: '超出最大限制3，添加失败',
        type: 'error',
    })
}

const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()

    axios.get("/api/GetUserInfo?RYD_UserId=" + RYD_UserId).then(res => {
        ruleForm.value.RYD_UserName = res.realName;
    })
}

const handleRemove = (file) => {
    fileArr.value.splice(fileArr.value.indexOf(file), 1)
    urlImage = urlImage.replace(file.name + "|", '')
}





initData();
function initData() {

    Promise.all(
        [
            axios({
                method: 'get',
                url: '/api/DemandLevels',
            }).then(res => {
                levelColumns.value = res;
            }),

            axios({
                method: 'get',
                url: '/api/GetCompany?RYD_UserId=' + RYD_UserId
            }).then(res => {
                RYD_Company.value = res;
                axios({
                    method: 'get',
                    url: '/api/GetDemandTypes?RYD_Company=' + res,
                }).then(res => {
                    levelColumnsDemandType.value = res;
                })
            }),

            axios.get("/api/GetUserInfo?RYD_UserId=" + RYD_UserId).then(res => {
                ruleForm.value.RYD_UserName = res.realName;
            })
        ]
    ).then(() => {
        // console.log("🚀 ~ file: WindowsAddDemand.vue ~ line 189 ~ initData ~ res", res)
        loading.value = false;
        if (props.editDemandId != null) {

            axios({
                method: 'get',
                url: '/api/DemandInfo?RYD_DemandId=' + props.editDemandId
            }).then(res => {
                // ruleForm.value.RYD_UserName = res.ryD_UserName;
                ruleForm.value.RYD_UserAddress = res.ryD_UserAddress;
                ruleForm.value.RYD_UserIp = res.ryD_UserIp;
                ruleForm.value.RYD_UserPhone = res.ryD_UserPhone;
                ruleForm.value.RYD_TypeId = res.ryD_TypeId;
                ruleForm.value.RYD_Level = res.ryD_Level + '';
                ruleForm.value.RYD_DemandDetails = res.ryD_DemandDetails;
                if (res.ryD_Files != null && res.ryD_Files != "") {

                    urlImage = res.ryD_Files;
                    if (urlImage != null) {
                        urlImage += "|";
                    }
                    res.ryD_Files.split('|').forEach(element => {
                        fileArr.value.push(
                            {
                                name: element,
                                url: element
                            }
                        );
                    });
                }
                // loadingInfo.value = false;
            })
        } else {
            axios({
                method: 'get',
                url: '/api/GetLastDemand?RYD_Id=' + RYD_UserId,
            }).then(res => {
                if (res != null && res != "") {
                    dialogVisible2.value = true;
                    ruleFormRes.value = res;

                }
            })
        }
    })
}

</script>
<style>
.DemandFileImage {
    width: 100%;
}

.removeSpan {
    position: absolute;
    right: 0;
    top: 0;
    background-color: rgb(143, 143, 143);
    height: 20px;
    width: 20px;
    text-align: center;
    line-height: 20px;
    color: #fff;
    border-radius: 0 5px 0 5px;
    cursor: pointer;
}
</style>